<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import { purchasePlanDetailApi } from '@/pages/purchase/components/PurchasePlanDetail'
import type {   PurchasePlanDetail,PurchasePlanDetailModel,PurchasePlanDetailListResponse,FormItemConfig } from "@/pages/purchase/components/PurchasePlanDetail" 

const currentPlanId = ref<number | null>(null)
const currentPlanName = ref<string | null>(null)

const availablePlans = ref([
  { id: 101, name: '年度采购计划A' },
  { id: 102, name: '季度采购计划B' },
  { id: 103, name: '紧急采购计划C' },
]);

const deviceNamesOptions = ref<{ label: string; value: string; }[]>([]);
const deviceModelsOptions = ref<{ label: string; value: string; }[]>([]);
const supplierNamesOptions = ref<{ label: string; value: string; }[]>([]);


const ListFields = [
    {
      label: '详情ID',
      prop: 'purchasePlanDetailId',
      type: 'input',
      width: "80",
    },
    {
      label: '设备名称',
      prop: 'deviceName',
      type: 'input',
      minWidth: "120",
    },
    {
      label: '设备型号',
      prop: 'deviceModel',
      type: 'input',
      minWidth: "120",
    },
    {
      label: '数量',
      prop: 'quantity',
      type: 'input',
      width: "80",
    },
    {
      label: '供应商名称',
      prop: 'supplierName',
      type: 'input',
      minWidth: "120",
    },
    {
      label: '操作',
      prop: 'action',
      slot: true,
      width: "160"
    },
];

const formConfig: FormItemConfig[] = [
  {
    type: 'select',
    label: '设备名称',
    prop: 'deviceName',
    placeholder: '请选择设备名称',
    options: deviceNamesOptions,
    disabled: false,
  },
  {
    type: 'select',
    label: '设备型号',
    prop: 'deviceModel',
    placeholder: '请选择设备型号',
    options: deviceModelsOptions,
    disabled: ref(true),
  },
  {
    type: 'select',
    label: '供应商名称',
    prop: 'supplierName',
    placeholder: '请选择供应商名称',
    options: supplierNamesOptions,
    disabled: ref(true),
  },
  {
    type: 'input',
    label: '数量',
    prop: 'quantity',
    placeholder: '请输入数量',
    inputType: 'number',
    disabled: false,
  },
];

let purchasePlanDetailList = ref<PurchasePlanDetail[]>([]);
const formModel = ref<PurchasePlanDetailModel>({
  purchasePlanDetailId: null,
  planId: 0,
  deviceName: '',
  deviceModel: '',
  quantity: 0,
  supplierName: '',
  category:''
})

const bufferName = [
  { add: "添加采购设备" },
  { edit: "编辑采购设备x"}
]
const titleName = "采购设备详情";
const searchMessage = ref({
  deviceName:'',
  deviceModel:'',
  supplierName: '',
})

const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

const title = ref('')
const visibleDrawer = ref(false)

onMounted(async () => {
  const storedId = sessionStorage.getItem('currentPurchasePlanId')

  if (storedId) {
    currentPlanId.value = parseInt(storedId)
  }

  const storedName = sessionStorage.getItem('currentPurchasePlanName')
  if (storedName) {
    currentPlanName.value = storedName
  }
  await getDataListWithCondition()
  
  const res = await purchasePlanDetailApi.listDeviceNames();
  const myStringList = res.data;
  deviceNamesOptions.value = myStringList.map(item => ({
      label: item,
      value: item
    }));
  console.log(deviceNamesOptions.value);

})

watch(currentPlanId, async (newVal) => {
  if (newVal !== null) {
    const selectedPlan = availablePlans.value.find(plan => plan.id === newVal);
    if (selectedPlan) {
      currentPlanName.value = selectedPlan.name;
      sessionStorage.setItem('currentPurchasePlanId', String(newVal));
      sessionStorage.setItem('currentPurchasePlanName', selectedPlan.name);
    }
    await getDataListWithCondition();
  } else {
    currentPlanName.value = null;
    sessionStorage.removeItem('currentPurchasePlanId');
    sessionStorage.removeItem('currentPurchasePlanName');
    purchasePlanDetailList.value = [];
    total.value = 0;
  }
});
let isProgrammaticChange = false;

watch(() => formModel.value.deviceName, async (newVal, oldVal) => {
  if (newVal === oldVal) return;

  const deviceModelSelectConfig = formConfig.find(item => item.prop === 'deviceModel');
  const supplierNameSelectConfig = formConfig.find(item => item.prop === 'supplierName');

  if (!isProgrammaticChange) {
    formModel.value.deviceModel = '';
    formModel.value.supplierName = '';
    deviceModelsOptions.value = [];
    supplierNamesOptions.value = [];
  }

  // Always update disabled state based on newVal
  if (deviceModelSelectConfig) {
    (deviceModelSelectConfig as any)
    .disabled.value = !newVal;
  }
  if (supplierNameSelectConfig) {
    (supplierNameSelectConfig as any)
    .disabled.value = true;
  }

  if (newVal) {
    try {
      const res = await purchasePlanDetailApi.listDeviceModelsByDeviceName(newVal);
      deviceModelsOptions.value = res.data.map(item => ({ label: item, value: item }));
    } catch (error) {
      console.error('获取设备型号失败:', error);
      ElMessage.error('获取设备型号失败');
    }
  }
});

watch(() => formModel.value.deviceModel, async (newVal, oldVal) => {
  if (newVal === oldVal) return;

  if (!isProgrammaticChange) {
    formModel.value.supplierName = '';
    supplierNamesOptions.value = [];
  }

  const supplierNameSelectConfig = formConfig.find(item => item.prop === 'supplierName');
  // Always update disabled state based on newVal
  if (supplierNameSelectConfig) {
    (supplierNameSelectConfig as any)
    .disabled.value = !newVal;
  }

  if (newVal && formModel.value.deviceName) {
    try {
      const res = await purchasePlanDetailApi.listSupplierNames(formModel.value.deviceName, newVal);
      supplierNamesOptions.value = res.data.map(item => ({ label: item, value: item }));
    } catch (error) {
      console.error('获取供应商名称失败:', error);
      ElMessage.error('获取供应商名称失败');
    }
  }
});


const getDataListWithCondition = async () => {
    if (currentPlanId.value === null) {
      purchasePlanDetailList.value = []
      total.value = 0
      return
    }

    let params: {
      planId: number,
      page: number,
      size: number,
      deviceName?: string | null,
      deviceModel?: string | null,
      supplierName?: string | null
    } = {
        planId: currentPlanId.value,
        page: pageNum.value,
        size: pageSize.value,
        deviceName: searchMessage.value.deviceName || null,
        deviceModel: searchMessage.value.deviceModel || null,
        supplierName: searchMessage.value.supplierName || null,
    }

    try {
        const axiosResponse = await purchasePlanDetailApi.listPurchasePlanDetails(params);
        const responseData: PurchasePlanDetailListResponse = axiosResponse.data;
        
        purchasePlanDetailList.value = responseData.records;
        total.value = responseData.total;
        
        console.log("获取到的采购计划详情:", responseData);
    } catch (error) {
        console.error("获取采购计划详情失败:", error);
        ElMessage.error("获取采购计划详情失败");
    }
}

const handleSubmit = async () => {
  if (currentPlanId.value === null) {
    ElMessage.error("无法提交:缺少关联的计划ID。");
    return;
  }
  
  formModel.value.planId = currentPlanId.value;

  try {
    if (formModel.value.purchasePlanDetailId) {
        ElMessage.success('更新成功');
      } else {
        await purchasePlanDetailApi.addPurchasePlanDetail(formModel.value);
        ElMessage.success('添加成功');
      }
      visibleDrawer.value = false;
      getDataListWithCondition();
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error('提交失败，请检查输入或网络');
  }
}


const showEditDrawer = async (row: PurchasePlanDetail) => {
    title.value = bufferName[1].edit!;
    isProgrammaticChange = true;

    formModel.value = { ...row };

    const deviceModelConfig = formConfig.find(item => item.prop === 'deviceModel');
    const supplierNameConfig = formConfig.find(item => item.prop === 'supplierName');

    try {
        if (row.deviceName) {
            const modelsRes = await purchasePlanDetailApi.listDeviceModelsByDeviceName(row.deviceName);
            deviceModelsOptions.value = modelsRes.data.map((item: string) => ({ label: item, value: item }));
            if (deviceModelConfig) (deviceModelConfig as any).disabled.value = false; // Enable deviceModel select
        } else {
            if (deviceModelConfig) (deviceModelConfig as any).disabled.value = true; // Disable if no deviceName
        }

        if (row.deviceName && row.deviceModel) {
            const suppliersRes = await purchasePlanDetailApi.listSupplierNames(row.deviceName, row.deviceModel);
            supplierNamesOptions.value = suppliersRes.data.map((item: string) => ({ label: item, value: item }));
            if (supplierNameConfig) (supplierNameConfig as any).disabled.value = false; // Enable supplierName select
        } else {
            if (supplierNameConfig) (supplierNameConfig as any).disabled.value = true; // Disable if no deviceModel
        }
    } catch (error) {
        console.error('Failed to load data for editing:', error);
        ElMessage.error('加载编辑数据失败');
    } finally {
        visibleDrawer.value = true;
        setTimeout(() => {
            isProgrammaticChange = false;
        }, 0);
    }
};

const deletefor = async (detailId: number) => {
  try {
    await purchasePlanDetailApi.deletePurchasePlanDetail(detailId);
    ElMessage.success('删除成功');
    getDataListWithCondition();
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error("删除失败，请重试");
  }
}

const deleteBox = (detailId: number) => {
    ElMessageBox.confirm(
        '您确定要删除这条记录吗',
        '注意',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    .then(() => {
        deletefor(detailId)
    })
    .catch(() => {
        ElMessage({
            type: 'info',
            message: '删除取消',
        })
    })
}

const search = () => {
    pageNum.value = 1
    getDataListWithCondition()
    ElMessage('获取成功')
}

const searchWithNoCondition = () => {
    searchMessage.value = { deviceName: '', deviceModel: '', supplierName: '' }
    pageNum.value = 1
    getDataListWithCondition()
    ElMessage('获取成功')
}

const onSizeChange = (size: number) => {
    pageSize.value = size
    getDataListWithCondition()
    ElMessage('获取成功')
}

const onCurrentChange = (num: number) => {
    pageNum.value = num
    getDataListWithCondition()
    ElMessage('获取成功')
}
</script>

<template>
  <el-card class="page-container">
    <template v-if="currentPlanId== null">
        <div class="header">
            <span>请从采购计划中选择某一计划查看详情</span>
        </div>
    </template>
    <template #header v-if="currentPlanId !== null" >
        <div class="header">
            <span>{{ titleName }}-------{{ currentPlanName }}</span>
        </div>
    </template>

    <template v-if="currentPlanId !== null">
      <el-form inline>
        <el-form-item label="设备名称:">
          <el-input v-model="searchMessage.deviceName" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="设备型号:">
          <el-input v-model="searchMessage.deviceModel" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="供应商名称:">
          <el-input v-model="searchMessage.supplierName" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item>
        <el-button type="primary" @click="search()">搜索</el-button>
           <el-button @click="searchWithNoCondition()">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="purchasePlanDetailList" style="width: 100%">
        <el-table-column
          v-for="col in ListFields"
          :key="col.prop"
          :label="col.label"
          :prop="col.prop"
          :width="col.width"
          :min-width="col.minWidth"
        >
          <template v-if="col.slot" #default="scope">
            <template v-if="col.prop === 'action'">
              <el-button
                :icon="Edit"
                circle
                plain
                type="primary"
                @click="showEditDrawer(scope.row)"
              ></el-button>
              <el-button
                :icon="Delete"
                circle
                plain
                type="danger"
                @click="deleteBox(scope.row.purchasePlanDetailId)"
              ></el-button>
            </template>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="没有数据" />
        </template>
      </el-table>
      <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 10]"
          layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
          @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />


    <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
      <el-form :model="formModel" label-width="120px">
        <template v-for="(item, index) in formConfig" :key="index">
          <el-form-item v-if="item.type === 'input'" :label="item.label">
            <el-input
              v-model="formModel[item.prop]"
              :placeholder="item.placeholder"
              :type="item.inputType === 'number' ? 'number' : 'text'"
            ></el-input>
          </el-form-item>

          <el-form-item v-else-if="item.type === 'select'" :label="item.label">
            <el-select
              v-model="formModel[item.prop]"
              :placeholder="item.placeholder"
              clearable
              style="width: 100%"
              :disabled="item.disabled"
            >
              <template v-if="item.options">
                <el-option
                  v-for="option in item.options.value"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value" />
              </template>
            </el-select>
          </el-form-item>
        </template>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    </template>
  </el-card>
</template>



<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}
.my-select {
  width: 250px;
}
</style>